using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using NfsEngine;

namespace NeedForSpeed
{
    static class TrackBillboardModel
    {
        static VertexPositionTexture[] _vertices;
        static VertexBuffer _vertexBuffer;
        static VertexDeclaration _vertexDeclaration;

        static TrackBillboardModel()
        {
            CreateGeometry();
            _vertexDeclaration = new VertexDeclaration(Engine.Instance.Device, VertexPositionTexture.VertexElements);
        }

        public static void BeginBatch()
        {
            Engine.Instance.Device.Vertices[0].SetSource(_vertexBuffer, 0, VertexPositionTexture.SizeInBytes);
            Engine.Instance.Device.VertexDeclaration = _vertexDeclaration;

            Engine.Instance.CurrentEffect.CurrentTechnique.Passes[0].Begin();
        }

        public static void EndBatch()
        {
            Engine.Instance.CurrentEffect.CurrentTechnique.Passes[0].End();
        }

        public static void Render(Matrix world, Texture2D texture)
        {
            BasicEffect effect = Engine.Instance.CurrentEffect;
            effect.World = world;
            effect.Texture = texture;
            effect.CommitChanges();
            
            Engine.Instance.Device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
        }

        private static void CreateGeometry()
        {
            Vector3 topLeftFront = new Vector3(-0.5f, 1.0f, 0.5f);
            Vector3 bottomLeftFront = new Vector3(-0.5f, 0.0f, 0.5f);
            Vector3 topRightFront = new Vector3(0.5f, 1.0f, 0.5f);
            Vector3 bottomRightFront = new Vector3(0.5f, 0.0f, 0.5f);
            
            Vector2 textureTopLeft = new Vector2(0.0f, 0.0f);
            Vector2 textureTopRight = new Vector2(1.0f, 0.0f);
            Vector2 textureBottomLeft = new Vector2(0.0f, 1.0f);
            Vector2 textureBottomRight = new Vector2(1.0f, 1.0f);

            _vertices = new VertexPositionTexture[4];
            _vertices[0] = new VertexPositionTexture(topLeftFront, textureTopLeft);
            _vertices[1] = new VertexPositionTexture(bottomLeftFront, textureBottomLeft);
            _vertices[2] = new VertexPositionTexture(topRightFront, textureTopRight);
            _vertices[3] = new VertexPositionTexture(bottomRightFront, textureBottomRight);

            _vertexBuffer = new VertexBuffer(Engine.Instance.Device,
                                                 VertexPositionTexture.SizeInBytes * _vertices.Length,
                                                 BufferUsage.WriteOnly);

            _vertexBuffer.SetData<VertexPositionTexture>(_vertices);
        }

    }


}
